<template>
    <el-card shadow="hover" :body-style="{ padding: '20px' }">
        <div slot="header">
            <el-button type="primary" :icon="Plus" @click="addTradeMark">添加</el-button>
        </div>
        <!-- card body -->


        <el-table style="margin:20px 0px" border :data="tmObj.records" v-loading="loading"
            element-loading-text="努力加载中..." element-loading-background="rgba(122, 122, 122, 0.2)">
            <el-table-column label="序号" width="90" align="center" type="index">
            </el-table-column>
            <el-table-column label="品牌名称" prop="tmName">
            </el-table-column>
            <el-table-column label="品牌LOGO">
                <template #="{row,$index}">
                    <img :src="row.logoUrl" alt="" style="width:80px; height:60px">
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #="{ row, $index }">
                    <el-button type="warning" size="small" :icon="Edit" @click="updateTradeMark(row)"></el-button>

                    <el-popconfirm :title="`你确定删除${row.tmName}?`" width="250px" :icon="Delete" @confirm="handler(row)">
                        <template #reference>
                            <el-button type="danger" size="small" :icon="Delete"></el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination background layout=" prev, pager, next, jumper,->,sizes,total, " :total="tmObj.total"
            :page-sizes="[3,6,9]" :pager-count="7" v-model:current-page="currentPage" v-model:page-size="pageSize"
            @current-change="getTradeMarkList" @size-change="sizeHandler" />



        <!-- 添加框 -->
        <el-dialog title="添加品牌" draggable v-model="dialogFormVisible">
            <el-form label-width="90px" style="width: 80%" ref="formRef" :model="tmParams" :rules="rules">
                <el-form-item label="品牌名称" prop="tmName">
                    <el-input autocomplete="off" style='margin:10px,0px' v-model="tmParams.tmName" />
                </el-form-item>
                <el-form-item label="品牌LOGO" prop="logoUrl">
                    <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="tmParams.logoUrl" :src="tmParams.logoUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="addOrUpdate">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </el-card>


</template>

<script setup lang="ts">
//引入element-plus提供的图标库组件
import {
    Check,
    Delete,
    Edit,
    Message,
    Search,
    Star,
    Plus
} from '@element-plus/icons-vue'
//引入请求函数
import { reqTrademark, reqAddOrUpdateTradeMark, reqDeleteTradeMark } from '@/api/product/trademark/trademark'
// 引入数据类型
import type { trademark, trademarkResponseData } from '@/api/product/trademark/model/trademark'

import { ref, reactive, onMounted, nextTick } from "vue"

import { ElMessage } from 'element-plus'

import type { UploadProps, FormInstance, FormRules } from 'element-plus'
//收集新增品牌数据-将来发送请求携带给服务器
let tmParams = reactive<trademark>({
    tmName: '',
    logoUrl: '',
});
//保存分页器当前页码【当前第几页】
let currentPage = ref<number>(1);
//保存当前页面显示几条数据
let pageSize = ref<number>(3);
//定义控制loading效果响应式数据
let loading = ref<boolean>(false);
//定义添加框的显示与隐藏
let dialogFormVisible = ref<boolean>(false);
//定义接收服务器返回的品牌数据：total|records
let tmObj = reactive<trademarkResponseData>({
    total: 0,
    records: [],
});
//储存组件实例el-form
let formRef = ref<FormInstance>();
//组件挂载完毕需要先获取一次品牌数据：第一页，三条数据
onMounted(() => {
    getTradeMarkList(1);
});
//获取品牌数据的函数
//由于当前函数作为分页器的回调函数：element-plus底层会注入当前页面
const getTradeMarkList = async (page: number = 1) => {
    //参数整理一下
    currentPage.value = page
    //发送请求之前加载loading
    loading.value = true;
    //再次发送请求
    let result = await reqTrademark(currentPage.value, pageSize.value);
    //保存服务器返回的数据
    tmObj.total = result.total;//数据总条数
    tmObj.records = result.records;//品牌的数据
    //服务器返回数据以后loading关闭
    loading.value = false;
};
//右下角点击下拉框获取最新数据
const sizeHandler = (limit: number) => {
    //整理参数
    pageSize.value = limit;
    //再次发送请求
    getTradeMarkList();
}

//获取上传图片信息
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile

) => {
    tmParams.logoUrl = response.data;
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    //图片相关的信息
    //外层约束类型
    if (
        rawFile.type == "image/jpeg" ||
        rawFile.type == "image/png" ||
        rawFile.type == "image/gif"
    ) {
        //约束大小1024B->1K->1M->1G->1T
        if (rawFile.size / 1024 / 1024 <= 5) {
            return true;
        }
    } else {
        return false;
    }
};
//确定按钮的回调
const addOrUpdate = async () => {
    //触发el-form组件实例的validate方法，对表单进行验证
    formRef.value?.validate(async (success) => {
        //如果全部验证成功
        if (success) {
            //添加品牌或者修改品牌的请求
            await reqAddOrUpdateTradeMark(tmParams);
            //对话框关闭
            dialogFormVisible.value = false;
            //再次获取最新的全部商品的数据
            //如果是新增品牌分页器留在第一页没如果是修改留在当前页
            getTradeMarkList(tmParams.id ? currentPage.value : 1);
            //添加成功显示文字信息
            ElMessage({
                type: 'success',
                message: tmParams.id ? '修改品牌成功' : '添加品牌成功',
            })
        } else {
            ElMessage({
                type: 'warning',
                message: '操作失败'
            })
        }
    })

};
//添加按钮的事件回调
const addTradeMark = () => {
    //显示对话框
    dialogFormVisible.value = true;
    //每次对话框显示之前清空数据
    tmParams.tmName = '',
        tmParams.logoUrl = '',
        tmParams.id = '',

        //每次点击按钮重置表单验证信息
        // formRef.value?.resetFields();
        //当响应式数据发生变化页面重新渲染获取最新数据
        //nextTick是异步操作可以等数据回来以后限制表单验证
        nextTick(() => {
            formRef.value?.resetFields();
        })
}
//修改数据
const updateTradeMark = (row: trademark) => {
    //弹出对话框
    dialogFormVisible.value = true,
        //修改已有品牌数据
        nextTick(() => {
            //重置初始化，再次重新赋值
            //重置该表单，将其值重置为初始值
            formRef.value?.resetFields();
            // 重新获取数据
            tmParams.id = row.id;
            tmParams.logoUrl = row.logoUrl;
            tmParams.tmName = row.tmName;
        });
};

//自定义表单验证
const validatetmName = (rule: any, value: any, next: any) => {
    //rule:验证规则对象
    //value：内容
    //next：函数，放行函数
    //正则对象test：符合条件返回真，否则返回false
    if (value.length > 2) {
        next();
    } else {
        next(new Error('输入品牌的名称要大于2个字符的哦'))
    }
};

//表单验证
const rules = reactive<FormRules>({
    //tmName品牌名字
    tmName: [
        //required:验证框前面加上星星，
        //message：触发这个规则的时候提示错误信息
        //trigger：触发规则。失去焦点：blur，文本变化：change
        //min：2  文本最小值
        //max：10  文本最大值
        { required: true, trigger: 'blur', validator: validatetmName },
    ],
    logoUrl: [{ required: true, message: '请上传你最炫酷的图片' }],
});

//删除数据
const handler = async (row: trademark) => {
    try {
        await reqDeleteTradeMark(row.id);
        //提示信息
        ElMessage({
            type: "success",
            message: `删除${row.tmName}成功`,
        });
        getTradeMarkList(currentPage.value);
    } catch (error) {

    }
}
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
    
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>